package com.myzl.coal.client.device;

import cn.hutool.core.date.DateUtil;
import com.myzl.coal.client.CacheData;
import com.myzl.coal.domain.Rfid;
import com.myzl.coal.domain.dto.RealTimeDataDTO;
import com.myzl.coal.mapper.RfidMapper;
import com.myzl.coal.mq.MqService;
import com.myzl.coal.service.IDemoService;
import com.myzl.coal.service.IRfidCardService;
import com.myzl.coal.service.IRfidService;
import com.myzl.coal.utils.HexUtil;
import com.myzl.common.enums.CurrencyEnum;
import com.myzl.common.enums.DemoEnum;
import com.myzl.common.enums.DeviceTypeEnum;
import com.rfid.bean.GPS_DataInfo;
import com.rfid.callBack.CallBack.R2000;
import com.rfid.uhf.controller.impl.ReaderR2000;
import com.rfid.uhf.service.ReaderR2000Service;
import com.rfid.uhf.service.impl.ReaderR2000ServiceImpl;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
@Data
public class CallBackR2000 implements R2000 {

    private final IRfidService rfidService;
    private final IRfidCardService rfidCardService;
    private final RfidMapper rfidMapper;
    private final IDemoService demoService;
    private final MqService mqService;
    private final CacheData cacheData;


    public ReaderR2000 connectRfid(String ip, int port) {
        ReaderR2000 reader = null;
        try {
            ReaderR2000Service service = new ReaderR2000ServiceImpl();
            reader = service.connect(ip, port, this);
            if (null == reader) {
                return null;
            }
            Thread.sleep(500);
            boolean result = service.setGPIO(reader, (byte) 2, (byte) 0);
            log.info("result:" + result);
            service.beginInvV2(reader);

        } catch (Exception e) {
            log.info("rfid连接报错：", e);
        }
        return reader;
    }

    public void  connect(String ip, int port){
        Thread thread = new Thread(() -> {
            ReaderR2000 readerR2000=null;
            while (readerR2000==null) {
                readerR2000 = connectRfid(ip, port);
                try {
                    TimeUnit.SECONDS.sleep(60);
                } catch (InterruptedException e) {
                    log.info("定时器异常：",e);
                }
            }
        });
        thread.start();
    }

    @Override
    public void readData(String data, String rssi, String antennaNo, String deviceNo, String direction, String communicationMode) {
        log.info("EPC " + data + " RSSI " + rssi + " antennaNo " + antennaNo + " deviceNo " + deviceNo);
        byte[] bytes1 = HexUtil.hexStringToByteArray(data);
        byte[] bytes2 = Arrays.copyOfRange(bytes1, 0, bytes1.length - 1);
        String deviceNum = new String(bytes2);

        Rfid rfidParams = new Rfid();
        rfidParams.setDeviceNum(deviceNum);
        List<Rfid> rfids = rfidService.selectRfidList(rfidParams);
        if (CollectionUtils.isEmpty(rfids)) {
            return;
        }

        Rfid rfid = rfids.get(0);
        if (demoService.getRedisPoliceFlag(DemoEnum.plat)){
            if (rfid.getSerialNumber()<3){
                return;
            }
        }

        rfid.setReportTime(new Date());
        rfidService.updateRfid(rfid);

    }

    @Override
    public void serialPortException(String name, boolean result) {
        log.info(" 串口号: " + name + " 结果: " + result);
    }

    @Override
    public void heartBeat(String value, String deviceNo, String communicationMode) {
        StringBuffer sb = new StringBuffer();
        sb.append(" 心跳值: ");
        sb.append(value);
        sb.append(" 设备号: ");
        sb.append(deviceNo);
        sb.append(" IP或串口号: ");
        sb.append(communicationMode);
        log.info(sb.toString());

        Integer deviceId = cacheData.getDeviceId(communicationMode, 20058);
        List<RealTimeDataDTO> realTimeDataList = new ArrayList<>();
        RealTimeDataDTO realTimeData = new RealTimeDataDTO();
        realTimeData.setDeviceId(deviceId);
        realTimeData.setDictValue(CurrencyEnum.REPORTING_TIME.getCode());
        realTimeData.setDeviceType(DeviceTypeEnum.SIEVE_PLAT.getCode());
        realTimeData.setDataValue(DateUtil.now());
        realTimeDataList.add(realTimeData);
        mqService.sendRealTimeData(realTimeDataList);
        mqService.sendDeviceStatusOnline(deviceId);

    }

    @Override
    public void infraredTrigger(boolean direction, String value, String deviceNo, String communicationMode) {
        StringBuffer sb = new StringBuffer();
        sb.append(" 红外触发进或入方向(0或1): ");
        sb.append(direction);
        sb.append(" 红外触发值: ");
        sb.append(value);
        sb.append(" 设备号: ");
        sb.append(deviceNo);
        sb.append(" IP或串口号: ");
        sb.append(communicationMode);

        log.info("rfid:infraredTrigger"+sb.toString());
    }

    @Override
    public void onceReadTagEnd(boolean result) {
        log.info(" 单次读卡结束: " + result);
    }

    @Override
    public void GPSInfo(GPS_DataInfo info) {
        log.info(info.getDeviceNo());
        log.info(info.getOriginalData());
    }
}